self = {
	/**
	 * websocket链接
	 */
	connectSocket: function() {
	  var that = this;
	  let app = getApp();
	  var userinfo = app.getUserinfo();
	  if (!userinfo || app.globalData.wsDomain == '' || (app.globalData.chat_config.SocketTask && app.globalData.chat_config.SocketTask.readyState == 1)) {
		return false;
	  }
	  let url = app.globalData.wsDomain + '?token=' +userinfo.token;
	  var SocketTask = wx.connectSocket({
		url: url,
		success: (res) => {
		  console.log('wss 连接成功');
		  wx.onNetworkStatusChange(function(res) {
			console.log(res.isConnected);
			console.log(res.networkType);
		  });
		}
	  });
	  app.globalData.chat_config.SocketTask = SocketTask;
	  SocketTask.onMessage((evt) => {
		var msg = JSON.parse(evt.data);
		if (msg.code == 0) {
		  wx.showModal({
			  title: '提示',
			  content: msg.msg || '网络错误',
			  showCancel:false
			})
		  return;
		}
		that.handleMsg(msg);
	  });
	  SocketTask.onOpen(() => {
		app.globalData.chat_config.CurrentRetryCount = 0; // 重新发送所有出错的消息
		if (app.globalData.chat_config.ErrorMsg.length > 0) {
		  for (let i in app.globalData.chat_config.ErrorMsg) {
			that.wsSend(app.globalData.chat_config.ErrorMsg[i]);
		  }
  
		  app.globalData.chat_config.ErrorMsg = [];
		}
  
		if (app.globalData.chat_config.Timer != null) {
		  clearInterval(app.globalData.chat_config.Timer);
		}
  
		app.globalData.chat_config.Timer = setInterval(that.wsSend, 29999); //定时发送心跳
	  });
	  SocketTask.onError(function(res) {
		console.log('wss:onError', res);
	  });
	  SocketTask.onClose(function(res) {
		console.log('关闭');
  
		if (app.globalData.chat_config.Timer != null) {
		  clearInterval(app.globalData.chat_config.Timer);
		}
  
		if (app.globalData.chat_config.MaxRetryCount) {
		  app.globalData.chat_config.Timer = setInterval(that.retryWebSocket, 3000); //每3秒重新连接一次
		}
	  });
	},
	/**
	 * 断线重连
	 */
	retryWebSocket: function(option = {}) {
	  var app = getApp();
	  if (app.globalData.chat_config.CurrentRetryCount < app.globalData.chat_config.MaxRetryCount) {
		app.globalData.chat_config.CurrentRetryCount++;
		self.connectSocket();
		console.log('重连 WebSocket 第' + app.globalData.chat_config.CurrentRetryCount + '次');
	  } else {
		if (app.globalData.chat_config.Timer != null) {
		  clearInterval(app.globalData.chat_config.Timer);
		}
		wx.showModal({
		  title: '提示',
		  content: 'Websocket连接失败',
		})
		// if (app.globalData.chat_config.ReConnection) {
		// 	console.log('每隔10秒将再次尝试重连 WebSocket');
		// 	app.globalData.chat_config.Timer = setInterval(this.connectSocket, 10000); //每10秒重新连接一次
		// }
	  }
	},
	/**
	 * 消息发送
	 */
	wsSend: function(message) {
	  var app = getApp();
	  if (!message) {
		message = {type: 'ping'};
	  }
	  if (app.globalData.chat_config.SocketTask && app.globalData.chat_config.SocketTask.readyState == 1) {
		app.globalData.chat_config.SocketTask.send({
		  data: JSON.stringify(message),
		  success: (res) => {
			// console.log(res);
		  },
		  fail: (res) => {
			// console.error(res);
		  }
		});
	  } else {
		console.log('消息发送出错', message);
		app.globalData.chat_config.ErrorMsg.push(message);
	  }
	},
	/**
	 * 推送来的消息处理
	 * @param {Object} ret
	 */
	handleMsg: function(ret) {
	  var app = getApp();
	  if(ret.code ==2){
		  return '';
	  }
	  switch (ret.type) {
		case 'login':
		  app.globalData.chat_config.emoList = ret.data.chat_memes; // 表情
		  app.globalData.chat_config.messageCount = ret.data.unread_num;
		   //底部未读消息
		  app.eventBus.emit(app.Events.WebsocketMessageCount,ret.data.unread_num)
		  break;
		case 'session_list':
		  // 处理会话列表
		  this.handleSessionList(ret.data);
		  break;
	  case 'del_chat':
		  // 删除会话
		  app.eventBus.emit('del_chat', ret.data);
		  break;
		case 'del_session':
		  // 删除会话
		  app.eventBus.emit('del_session', data);
		case 'msg_list':
		  // 聊天记录
		  var data = this.handleMsgList(ret);
		  app.eventBus.emit('msg_list_callback', data);
		  break;
		case 'new_msg':
		  // 好友发消息
		  this.newMsgList(ret.data);
		  this.setMessageBadge()
		  break;
		case 'say':
		  //我发送的消息，推给我
		  app.eventBus.emit('new_msg_callback', ret.data);
		  break;
		case 'set_read':
		  break;
		case "message_count":
		  // 设置底部菜单的角
		  app.globalData.chat_config.messageCount = ret.data.unread_num;
		  app.eventBus.emit(app.Events.WebsocketMessageCount,ret.data.unread_num)
		default:
		  break;
	  }
	},
	/**
	 * 发送消息
	 */
	sendMessage: function(receive_user_id,content, chat_type = 1) {
	  self.wsSend({
		type: 'say',
		receive_user_id: receive_user_id,
		content: content,
		chat_type: chat_type //类型:1=文字,2=图片,3=职位,4=投递,5=,6=人才,7=面试
	  });
	},
  
	//聊天进程列表分页
	handleSessionList: function(data) {
	  getApp().eventBus.emit('session_list_callback', data);
	},
	/**
	 * 聊天消息列表
	 */
	handleMsgList: function(ret) {
	  var res = ret.data;
	  if (res.total == 0) {
		return {
		  data: res,
		  receive_user: ret.receiveuser
		};
	  }
	  var array = [];
	  var new_arr = [];
	  var min_time = res.data[res.data.length - 1].createtime;
	  var min_time_text = res.data[res.data.length - 1].createtime_text;
	  array[min_time_text] = [];
	  for (let index = res.data.length - 1; index >= 0; index--) {
		const v = res.data[index];
		// 处理表情包
		v.message = v.type == 1 ? self.changeEmotion(v.message) : v.message; // 如果当前时间和最早时间相差不超过10分钟，就分为一组
  
		if (v.createtime - min_time <= 600) {
		  array[min_time_text].push(v);
		} else {
		  min_time = v.createtime;
		  min_time_text = v.createtime_text;
		  array[min_time_text] = [];
		  array[min_time_text].push(v);
		}
	  }
	  for (const key in array) {
		new_arr.push({
		  time: key,
		  data: array[key]
		});
	  }
	  res.data = new_arr;
	  return {
		data: res,
		receive_user: ret.receiveuser
	  };
	},
	//处理一个聊天列表分页-暂时未用到
	handle_msg_data: function(data) {
	  var new_arr = [];
  
	  data.message = data.type == 1 ? self.changeEmotion(data.message) : data.message;
	  new_arr.push({
		time: data.createtime_text,
		data: [data]
	  });
	  return {
		data: new_arr,
	  };
	},
	//好友发消息
	newMsgList: function(data) {
	  let pages = getCurrentPages();
	  if(pages[pages.length - 1].route == 'pages/communicate/index'){
		//如果在聊天室
		getApp().eventBus.emit('new_msg_callback', data);
	  }else{
		var currentPage = pages[pages.length - 1]; //获取当前页面的对象
		var url = currentPage.route; //当前页面url
  
		var arr = ['pages/indexpage/indexpage', 'pages/seek_job/seek_job','pages/looking_for_talent/looking_for_talent','pages/communicate_list/communicate_list','pages/invitation/invitation','pages/interview_invitation/interview_invitation','pages/user_center/user_center'
		];
		if (arr.indexOf(url) == -1) {
		  return false;
		}else{
		  getApp().eventBus.emit("refresh_session",{})
		}
	  }
	  // wx.vibrateLong({
	  // 	success: function() {
	  // 		console.log('震动成功');
	  // 		self.setMessageBadge(true);
	  // 	}
	  // });
	},
  
	/**
	 * 聊天消息-处理一个聊天记录按时间分组
	 */
	get_msg_list: function(receive_user_id, page) {
	  self.wsSend({
		type: 'msglist',
		page: page,
		receive_user_id: receive_user_id
	  });
	},
	// 设置底部菜单角标 有底部的页面onshow里都要调用该方法
	setMessageBadge: function(is_need_check = false) {
	  
	  if (is_need_check && getCurrentPages().length > 0) {
		var pages = getCurrentPages(); //获取加载的页面
		var currentPage = pages[pages.length - 1]; //获取当前页面的对象
		var url = currentPage.route; //当前页面url
  
		var arr = ['pages/indexpage/indexpage', 'pages/communicate_list/communicate_list','pages/seek_job/seek_job','pages/interview_invitation/interview_invitation','pages/user_center/user_center'
		];
  
		if (arr.indexOf(url) == -1) {
		  return false;
		}
	  }
	  //获取未读消息数
	  self.wsSend({
		type: 'getmessagecount'
	  });
	},
	//表情
	changeEmotion: function(contents) {
	  var emotions = getApp().globalData.chat_config.emoList;
	  var pattern1 = /\[[\u4e00-\u9fa5]+\]/g;
	  var pattern2 = /\[[\u4e00-\u9fa5]+\]/;
  
	  if (contents) {
		contents = contents.replace(new RegExp(/\<br>/, 'g'), '\n');
		contents = contents.replace(new RegExp(/\<br\/>/, 'g'), '\n');
	  }
  
	  var content = contents.match(pattern1);
	  var str = contents;
	  var now_str = contents;
	  var arr = [];
	  if (content == null)
		return [{
		  type: 1,
		  value: str
		}];
  
	  for (var i = 0; i < content.length; i++) {
		var src = '';
  
		for (var j = 0; j < emotions.length; j++) {
		  if (emotions[j].name == content[i]) {
			src = emotions[j].image;
			break;
		  }
		}
  
		if (!now_str) {
		  break;
		}
  
		var has_i = now_str.indexOf(content[i]);
  
		if (has_i != -1) {
		  arr.push({
			type: 1,
			value: now_str.substring(0, Number(has_i))
		  });
		  arr.push({
			type: 2,
			value: src
		  });
		  now_str = now_str.substring(Number(has_i) + Number(content[i].length));
  
		  if (i == content.length - 1) {
			arr.push({
			  type: 1,
			  value: now_str
			});
		  }
		}
	  }
  
	  return arr;
	},
  };
  
  module.exports = self;  